<?php

declare(strict_types=1);
/**
 * 本文件属于易云工作室馆版权所有，泄漏必究。
 * This file belong to YiYUN, all rights reserved.
 */
namespace Wyi\WebWechat;

use Wyi\WebWechat\extend\Helper;
use Wyi\WebWechat\request\Request;

class Qrcode
{
    const HOST = 'https://login.wx.qq.com';

    /**
     * @var Request
     */
    protected $request;

    /**
     * @var string
     */
    protected $uuid;

    /**
     * Qrcode constructor.
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * 获取微信登录二维表所需要的uuid.
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @return false|string
     */
    public function getUuid()
    {
        $uri = self::HOST . '/jslogin?appid=wx782c26e4c19acffb&redirect_uri=https%3A%2F%2Fwx.qq.com%2Fcgi-bin%2Fmmwebwx-bin%2Fwebwxnewloginpage&fun=new&lang=zh_&_=' . Helper::getTimestamp(13);
        $res = $this->request->sendGet($uri);
        if ($res->getStatusCode() != 200) {
            throw new \Exception('web wechat server error!');
        }
        $res = $res->getBody()->getContents();
        return Helper::getSubStr($res, ' window.QRLogin.uuid = "', '";');
    }

    /**
     * 获取登录二维码
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getLoginQRCode(string $uuid)
    {
        if (! $uuid) {
            throw new \Exception('uuid is empty');
        }
        $uri = self::HOST . '/qrcode/' . $uuid;
        $header = [
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36',
            'Accept' => 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
        ];
        $res = $this->request->sendGet($uri, $header);
        $res->getBody()->detach() ?? null;
    }

    /**
     * 检查二维码状态
     */
    public function checkQRCodeStatus(string $uuid,&$image = null)
    {
        // TODO 408正常 400过期 201已有设备扫码等待确认
        $uri = self::HOST . '/cgi-bin/mmwebwx-bin/login?loginicon=true&uuid=' . $uuid . '&tip=0&r=-256324513&_=' . Helper::getTimestamp(13);
        $res = $this->request->sendGet($uri);
        $resp = $res->getBody()->getContents();
        $res = explode(';',$resp);
        $item = $res[0] ?? '';
        switch ($item){
            case 'window.code=400':
                return ['code' => 400, 'msg' => '二维码已过期请重新获取'];
            case 'window.code=408':
                return ['code' => 408, 'msg' => '二维码检测正常'];
            case 'window.code=201':
                return ['code' => 201, 'msg' => '等待客户端确认', 'base64_img' => $this->getUserAvatar($res)];
            default :
                throw new \Exception('异常状态|'.$resp);
        }
    }

    /**
     * 获取正在扫码中的微信头像
     * @param array $data
     * @return false|string
     */
    private function getUserAvatar(array $data)
    {
        $r1 = $data[1] ?? '';
        $r2 = $data[2] ?? '';
        $res = $r1.$r2;
        return Helper::getSubStr($res,'\'','\'');

    }
}
